from langdev_helper.util.input import get_user_input
from langchain_core.messages import ToolMessage

def bp_main(app, thread):
    while True:
        user_input = get_user_input()
        if user_input == False:
            break

        # print('stream:', user_input)
        for event in app.stream({"messages": [("user", user_input)]}, thread, stream_mode="values"):
            message = event["messages"][-1]
            # print('message', message)
            message.pretty_print()

        snapshot = app.get_state(thread)
        while snapshot.next:
            print("Next action:->", snapshot.next)
            user_input = input(
                "Do you approve of the above actions? Type 'y' to continue;"
                " otherwise, explain your requested changed.\n\n"
            )
            
            if user_input.strip() == "y":
                print("Continuing...")
                result = app.invoke( None, thread,)
                # print('result:', result)
                print(result["messages"][-1].content)
            else:
                result = app.invoke(
                    {
                        "messages": [
                            ToolMessage(
                                tool_call_id=event["messages"][-1].tool_calls[0]["id"],
                                content=f"API call denied by user. Reasoning: '{user_input}'. Continue assisting, accounting for the user's input.",
                            )
                        ]
                    },
                    thread,
                )
            snapshot = app.get_state(thread)



def do_stream(user_input, graph, thread):
    events = graph.stream({"messages": [("user", user_input)]}, thread, stream_mode="values")
    last = None
    for event in events:
        message = event["messages"][-1]
        message.pretty_print()
        last = message.content
    if not last=='no':
        print('\nAI: ', last)

def mainloop(graph, thread):
    while True:
        try:
            user_input = get_user_input()
            if user_input == False:
                break

            do_stream(user_input, graph, thread)

        except Exception as e:
            print("Error: input() is not available: ", e)
            break